// pages/me/me.js
var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var user = require('../../services/user.js');
const pay = require('../../services/pay.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showWarning:false,
    isBusiness:false,
    userInfo: {},
    hasMobile: '',
    registerTime: '',
    role: '',
    token: '',
    mobile: '',
    details: {},
    point: '',
    myInfo:{},
    collectNum:0,
    footprintNum:0,
    typeId: 0,
    showWithdraw:false,
    balance:'',
    realName:'',
    inviteUserId:''
  },
  //打开提现
  openWithDraw(){
    this.setData({ showWithdraw: true });
  },
  //关闭提现
  onClose() {
    this.setData({ showWithdraw: false });
  },
  
  //登录
  bindGetUserInfo(e) {
    let userInfo = wx.getStorageSync('userInfo');
    let token = wx.getStorageSync('token');
    let router = wx.getStorageSync('Router')
    let url = wx.getStorageSync('Url')
    //登录并获取用户信息
    if (userInfo && token) {
      user.loginByWeixin(e.detail, data).then(res => {
        // console.log('res2==',res)
        if (res.errno == 0){
          this.setInfo(res, router, url)  
        }else{
          util.showErrorToast(res.msg)
        }
      }).catch((err) => {
        console.log(err)
      });
      return
    } else {
      if (e.detail.userInfo) {
        //用户按了允许授权按钮
        this.setData({ details: e.detail })
        user.loginByWeixin(e.detail).then(res => {
          // console.log('res1==' , res)
          if (res.errno == 0){
            this.setInfo(res,router,url)   
          }else{
            util.showErrorToast(res.msg)
          }
        }).catch((err) => {
          console.log(err)
        });
      } else {
        //用户按了拒绝按钮
        this.setData({ showWarning:true})
      }
    }

  },
  open(e){
    console.log(e)
  },
  cancel(){
    this.setData({showWarning:false})
  },
  // 获取手机号码
  getPhoneNumber(e) {
    if (e.detail.errMsg === 'getPhoneNumber:ok'){
      let data = { iv: e.detail.iv, encryptedData: e.detail.encryptedData }
      util.request(api.phoneNumber,data).then((res)=>{
        if (res.errno  == 0){
          util.showSuccessToast(res.errmsg)
          this.userInfo()
        }else{
          util.showErrorToast(res.errmsg)
        }
      })
    }
    
    
    
  },

  //核销（扫码二维码）
  scan(e){
    var formId = e.detail.formId
    wx.scanCode({
      onlyFromCamera: true,
      success(res) {
        let arr = res.result.split("&"); 
        let obj = {};
        for (let i of arr) {
          obj[i.split("=")[0]] = i.split("=")[1];  //对数组每项用=分解开，=前为对象属性名，=后为属性值
        }
        let order_id = obj.order_id
        let user_id = obj.userId
        let data = { order_id: order_id, user_id: user_id, formId: formId}
        util.post(api.verify,data).then((res)=>{
          if (res.errno == 0){
            util.showSuccessToast('核销成功')
          }else{
            util.showErrorToast('核销失败')
          }
        })
      }
    })
  },

  balance(e){
    this.setData({balance:e.detail.value})
  },
  realName(e){
    this.setData({ realName: e.detail.value })
  },
  // 提现
  withdraw(){
    if ( this.data.balance  >  this.data.myInfo.sellerInfo.avilableBalance){
      util.alert('输入金额不能大于可提现金额')
    }else{
      util.post(api.withdraw, { realName: this.data.realName, withdrawAmount:this.data.balance}).then((res)=>{
        if(res.code == 0){
          util.showSuccessToast('已提交，待审核')
          this.setData({ showWithdraw:false})
          this.userInfo()
        }else{
          util.alert(res.msg)
        }
      })
    }
  },

  // 质量保障弹框
  showAlert(){
    var _this = this
    wx.showModal({
      title: '提示',
      content: '为确保用户安心使用，建议您加入质量保障计划。加入则需缴纳5000元质量保障金，是否确认加入?',
      showCancel: true, //是否显示取消按钮-----》false去掉取消按钮
      cancelText: "取消", //默认是“取消”
      cancelColor: '#999999', //取消文字的颜色
      confirmText: "确认支付", //默认是“确定”
      confirmColor: '#108EE9', //确定文字的颜色
      success: function (res) {
        if (res.cancel) {
          //点击取消
          // console.log("您点击了取消")
        } else if (res.confirm) {
          pay.payCash(_this.data.myInfo.storeInfo.id).then((res)=>{
            // console.log(res)
          })
        }
      }
    })
  },

  userInfo(){
    let data = { 'userId': wx.getStorageSync('userId')}
    util.request(api.userInfo,data).then((res)=>{
      // console.log('aaa', res)
      if(res.errno == 0){
        if (res.data.user_level_id > 1){
          this.setData({ isBusiness:true})
        }else{
          this.setData({ isBusiness: false })
        }
        res.data.register_time = util.formatTime(new Date(res.data.register_time)).substring(0, 10)
        this.setData({myInfo:res.data})
        // console.log(this.data.myInfo)
      }
    })
  },

  // 登录后的操作
  setInfo(res, router,url){
    this.setData({
      userInfo: res.data.userInfo,
      token: res.data.token,
      point: res.data.userInfo.point
    });
    app.globalData.userInfo = res.data.userInfo;
    app.globalData.token = res.data.token;
    app.globalData.userId = res.data.userId
    wx.setStorageSync('userId', res.data.userId)
    if (router === '/pages/index/index') {
      wx.switchTab({
        url: url,
      })
    } else {
      wx.navigateTo({
        url: url,
      })
    }
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({ userInfo: wx.getStorageSync('userInfo') })
    this.userInfo()
    this.cancel()
    if (app.globalData.inviteUserId){
      this.setData({ inviteUserId: app.globalData.inviteUserId})
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})